package com.didi.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didi.gulimall.api.SecKillApiService;
import com.didi.gulimall.common.utils.PageUtils;
import com.didi.gulimall.common.utils.Query;
import com.didi.gulimall.common.utils.R;
import com.didi.gulimall.product.dao.SkuInfoDao;
import com.didi.gulimall.product.entity.SkuImagesEntity;
import com.didi.gulimall.product.entity.SkuInfoEntity;
import com.didi.gulimall.product.entity.SpuInfoDescEntity;
import com.didi.gulimall.product.service.*;
import com.didi.gulimall.product.to.SecKillSkuRedisTo;
import com.didi.gulimall.product.vo.Option;
import com.didi.gulimall.product.vo.SkuItemSaleAttrVo;
import com.didi.gulimall.product.vo.SkuItemVo;
import com.didi.gulimall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SecKillApiService secKillApiService;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 0,
     * brandId: 0,
     * min: 0,
     * max: 0
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (StringUtils.isNotBlank(min)) {
            BigDecimal minBigDecimal = new BigDecimal(min);
            wrapper.ge("price", minBigDecimal);
        }
        String max = (String) params.get("max");
        if (StringUtils.isNotBlank(max)) {
            BigDecimal maxBigDecimal = new BigDecimal(max);
            if (maxBigDecimal.compareTo(BigDecimal.ZERO) > 0) {
                wrapper.le("price", maxBigDecimal);
            }
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<Option> initSkuName() {
        return this.baseMapper.initSkuName();
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    @Cacheable(cacheNames = "item", key = "#root.args[0]", sync = false)
    public SkuItemVo getItem(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        SkuInfoEntity skuInfoEntity = infoFuture.get();
        if (skuInfoEntity == null) {
            return null;
        }

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.getItemBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);


        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(res -> {
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSkuSaleAttrValueBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            SpuInfoDescEntity infoDesc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(infoDesc);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getItemGroup(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

//        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
//            R r = secKillApiService.getSecKillBySkuId(skuId);
//            if (r.getCode() == 0) {
//                SecKillSkuRedisTo data = r.getData(new TypeReference<SecKillSkuRedisTo>() {
//                });
//                skuItemVo.setSeckillInfo(data);
//            }
//        }, executor);

        CompletableFuture.allOf(imageFuture, saleAttrFuture, descFuture, baseAttrFuture).get();

        return skuItemVo;
    }

    @Override
    public R getStringValue(Long skuId) {
        List<String> values = baseMapper.getStringValue(skuId);
        return R.ok().put("values", values);
    }

}
